﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Web.UI.WebControls;
using Ext.Net;
using Sio.Mdm.Entities;
using Sio.Mdm.BF.Ldap;
using Sio.Mdm.BF.Administracija;
using Sio.Mdm.Types.Database;
using Sio.Mdm.Web.Controls;

namespace Sio.Mdm.Web.Instalacija
{
    public partial class LdapPredlogeNovo : Controls.Page
    {
        #region schema*
        private static string schemaPath
        {
            get
            {
                string path = ConfigurationManager.AppSettings["ldapMigrationSchemaPath"];

                if (String.IsNullOrEmpty(path) || path == "default")
                {
                    path = AppDomain.CurrentDomain.BaseDirectory.ToString();
                }
                else
                {
                    if (path.Contains(":")) return path;

                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                }

                return path;
            }
        }

        private static string schemaDefaultPath
        {
            get
            {
                string path = ConfigurationManager.AppSettings["ldapMigrationSchemaDefaultPath"];

                if (String.IsNullOrEmpty(path) || path == "default")
                {
                    path = AppDomain.CurrentDomain.BaseDirectory.ToString();
                }
                else
                {
                    if (path.Contains(":")) return path;

                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                }

                return path;
            }
        }

        private static string schemaAD 
        {
            get {
                return "AD.xml";
            }
        }

        private static string schemaLDAP
        {
            get
            {
                return "openLdap.xml";
            }
        }

        private static string schemaFormat
        {
            get {
                return "{0}_{1}";
            }
        }

        private static string schemaFormatMulti
        {
            get
            {
                return "{0}_{1}_{2}";
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && !X.IsAjaxRequest)
            {                
                LoadOrgarnizacije();
                LoadLdapTipi();
            }
        }

        #region Load*
        private void LoadLdapTipi()
        {
            Dictionary<int, string> listTip = new Dictionary<int, string>();
            listTip.Add(0, "AD");
            listTip.Add(1, "LDAP");
            var tmpArray = (from p in listTip select new Object[2] { p.Key, p.Value }).ToArray();

            StoreLdapTipi.DataSource = tmpArray;
            StoreLdapTipi.DataBind();
        }

        private void LoadOrgarnizacije()
        {
            EntityCollection<Sio.Mdm.Types.Database.Organizacija> orgarnizacije = new EntityCollection<Sio.Mdm.Types.Database.Organizacija>(
                  new Filter<Sio.Mdm.Types.Database.Organizacija>().Where(o => o.OrganizacijaId != null).OrderBy(o => o.Naziv));
            StoreOrgarnizacije.DataSource = orgarnizacije;
            StoreOrgarnizacije.DataBind();
        }
        #endregion

        #region Save*
        private bool Save()
        {
            string templateSource = "";
            string templateTarget="";
            string schema ="";
            string schemaNewFileName="";

            if (cmbTip.SelectedItem.Text == "AD") {
                templateSource = Path.Combine(schemaDefaultPath, schemaAD);
                schema = schemaAD;
            }
            else {     
                templateSource = Path.Combine(schemaDefaultPath, schemaLDAP);
                schema = schemaLDAP;
            }

            if (!File.Exists(templateSource))
            {
                lblWarning.Show();
                lblWarning.Text = String.Format("Privzete poti za predlogo ni mogoče najti!! Iskana datoteka: {0}", templateSource);
                return false;
            }

            if (!Directory.Exists(schemaPath))
            {
                lblWarning.Show();
                lblWarning.Text = String.Format("Poti za hranjenje predlog ni mogoče najti!! Iskana pot: {0}", schemaPath);
                return false;
            }
                                     
            schemaNewFileName = String.Format(schemaFormat, cmbOrgarnizacije.SelectedItem.Value, schema);
            templateTarget = Path.Combine(schemaPath,schemaNewFileName);

            if (!File.Exists(templateTarget)) {
                return SaveNewSchema(templateSource, templateTarget, schemaNewFileName);                
            }

            int i = 1;            
            while (File.Exists(templateTarget))
            {
                i++;                
                schemaNewFileName = String.Format(schemaFormatMulti, cmbOrgarnizacije.SelectedItem.Value, schema, i);
                templateTarget = Path.Combine(schemaPath, schemaNewFileName);
            }
            return SaveNewSchema(templateSource, templateTarget, schemaNewFileName);
        }

        private bool SaveNewSchema(string source, string destination, string fileName)
        {
            try
            {
                File.Copy(source, destination);
                
                LdapPredloga predloga = EntityFactory.CreateInstance<LdapPredloga>();
                predloga.OrgarnizacijaID = Convert.ToInt32(cmbOrgarnizacije.SelectedItem.Value);
                predloga.Ime = txtIme.Text;
                predloga.Opis = txtOpis.Text;
                predloga.Datoteka = fileName;
                predloga.Update();
            }
            catch (Exception ex)
            {
                lblWarning.Show();
                lblWarning.Text = String.Format("Napaka pri shranjevanju predloge!! Napaka: {0}", ex.Message);
                return false;
            }

            return true;
        }
        #endregion

        #region DirectMethods
        [DirectMethod]
        protected void ButtonClicked(object sender, DirectEventArgs e)
        {
            DialogButtons button = e.DeserializeParameter<DialogButtons>("buttonType");

            if (button == DialogButtons.Save)
            {
                if (Save())
                    LdapPredlogeNovoProxy.Close();
            }            
        }
        
        #endregion
    }
}
